import Taro, {Component} from '@tarojs/taro'
import {View,Icon, Input, Image, Text, Textarea, Picker, Button, Label, Checkbox} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import styles from './index.module.scss'
import {AtIcon, AtButton, AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import SIGN_TIME_IMG from '@/assets/img/sign_time.png'
import {getTaskList, getRobbedList, submitOrderByTask, confirmOrderByTask, getProtocolByTask, updateOrderByTask, uploadFile, clockIn} from '@/api/index'
import { dialog} from '@/util/index';
import { setTaskFun } from '@/actions/task'
import { setUrl } from '@/actions/web'
import NoData from "@/components/NoData"
import bmap from '@/util/bmap-wx.min.js'
import { BMapAk, MINX_URL } from '@/api/config'

@connect(({user, task}) => ({
  info: user.info,
  isSign: user.isSign,
  merchant:task.merchant
}), dispatch => ({
  setTaskInfo:(data)=>dispatch(setTaskFun(data)),
  setUrl: (data) => dispatch(setUrl(data)),
}))
export default class taskList extends Component {

  config = {
    navigationBarTitleText: '任务列表'
  }

  state = {
    pageIndex:1,
    allLoadFlag:false,
    taskList:[],
    merchantName:'',
    id:1,
    isDialog: false,
    dialogContent: '',
    orderNumber: '',
    isContent: false,
    content: '',
    beginTime: undefined,
    endTime: undefined,
    statusList: {
      1: '未接单',
      2: '进行中',
      3: '待验收',
      4: '已驳回',
      5: '已验收',
      6: '已完成',
      7: '已取消',
      8: '已关闭'
    },
    address: '',
    clockInSuccess: false,
    uploadName: '',
    uploadPath: '',
    checkedItem: ''
  }

  componentWillMount = () => {}

  componentDidShow = () => {
    this.selectMer();
  }

  openGps = () => {
    wx.getLocation({
      type: 'gcj02',
      success:(res) => {
        this.getGeo()
      },
      fail: (e) => {
        dialog.toast({title: '获取定位失败，请重新定位'})
      }
    })
  }

  getSetting = () => {
    let that = this
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] == undefined) {
          this.openGps()
        } else if (res.authSetting['scope.userLocation'] == false) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    console.log(dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      that.getGeo();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else{
          this.getGeo()
        }
      }
    })
  }

  getGeo = () => {
    let that = this
    const BMap = new bmap.BMapWX({ak: BMapAk})
    let fail = (data) => console.log(data)
    let success = (data) => {
      let originalData = data.originalData
      let wxMarkerData = data.wxMarkerData
      if (originalData.status === 0) {
        this.clockInSync(wxMarkerData[0].latitude, wxMarkerData[0].longitude, wxMarkerData[0].address)
      } else {
        wx.showModal({
          title: '百度地图提示',
          content: '错误码：' + originalData.status
        })
      }
    }
    BMap.regeocoding({
      fail: fail,
      success: success,
      iconPath: '../assets/img/marker_red.png',
      iconTapPath: '../assets/img/marker_red.png'
    })
  }

  clockInSync = async (lat, lng, address) => {
    try {
      const { checkedItem } = this.state
      const { taskNumber } = checkedItem
      const { data } = await clockIn({taskNumber, lat, lng})
      this.setState({clockInSuccess: true, address})
      dialog.toast({title: '定位成功'})
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  getTaskList = async () => {
    const { merchantName, pageIndex, beginTime, endTime, id} = this.state;
    try {
      Taro.showLoading({mask: true, title: '数据加载中...'})
      const { data } = await getTaskList({merchantName, beginTime, endTime, pageIndex, loginAccount: this.props.info.mobile, status: id })
      Taro.hideLoading()
      let arr = data.map(item => {
        return Object.assign({}, item, {checked: true})
      })
      if (data && data.length>0) {
        this.setState(pre => ({taskList: [...pre.taskList, ...arr]}));
        data.length < 10 && this.setState({allLoadFlag:true})
      }else{
        this.setState({allLoadFlag:true})
      }
    } catch(e) {
      return dialog.toast({title: e.message});
    }
  }
  onReachBottom(){
    if(this.state.allLoadFlag==false){
      this.setState(prevState=>({pageIndex:++prevState.pageIndex}),()=>{
        this.getTaskList();
      })
    }else{
      return dialog.toast({title: '没有更多了'});
    }
  }

  selectMer(){
    this.setState({taskList:[], allLoadFlag:false, pageIndex:1},()=>{
      this.getTaskList();
    })
  }

  inputMer(e){
    this.setState({merchantName: e.detail.value});
    if(!e.detail.value){
      this.setState({merchantName: e.detail.value, allLoadFlag:false, pageIndex:1, taskList:[]},()=>{
        this.getTaskList();
      });
    }
  }

  selectTabs(item){
    this.setState({id: item.status, pageIndex: 1, taskList:[], allLoadFlag:false}, () => {
      this.getTaskList()
    });
  }

  confirm(item) {
    if (item.status === 1) {
      if (!item.checked) return
      this.AcceptOrder(item.taskNumber)
    } else if ([2, 4].includes(item.status)) {
      this.setState({orderNumber: item.orderNumber, isDialog: true, checkedItem: item})
    } else if (item.status === 7) {
      this.AcceptOrder(item.taskNumber)
    } else {
      this.showContent(item)
    }
  }

  showContent(item) {
    this.setState({content: item.taskDeliveryDescription, isContent: true})
  }

  async AcceptOrder(taskNumber) {
    try {
      Taro.showLoading({mask: true, title: '接单中'})
      const { data } = await submitOrderByTask({loginAccount: this.props.info.mobile, taskNumber})
      Taro.hideLoading()
      dialog.toast({title: '接单成功'})
      this.setState({id: 1}, () => {
        this.selectMer()
      })
    } catch (e) {
      dialog.toast({title: e.message})
    }
  }

  closeDialog = (callback) => {
    this.setState({isDialog: false, dialogContent: '', uploadName: '', uploadPath: '', address: ''}, () => {
      if (callback) {
        callback()
      } else {
        return
      }
    })
  }

  upLoadFileByFile = async () => {
    const { uploadPath } = this.state
    if (!uploadPath) return this.confirmOrder()
    let res = await Taro.uploadFile({
      url: MINX_URL('/common/upload'),
      filePath: uploadPath,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
    })
    if (res.statusCode === 200) {
      const result = JSON.parse(res.data)
      if (result.code === 0) {
        this.setState({uploadPath: result.url}, () => {
          this.confirmOrder()
        })
      }
    } else {
      dialog.toast({title: '上传失败'})
    }
  }

  /**
   * @description 交付任务
   * @param {address, deliveryAccessories, taskDeliveryDescription, status, orderNumber}
   */
  async confirmOrder() {
    try {
      const { orderNumber, dialogContent, address, uploadPath, clockInSuccess, checkedItem } = this.state
      const { info } = this.props
      const { onSiteCheckIn } = checkedItem
      if (!dialogContent) return dialog.toast({title: '请输入交付内容'})
      if (onSiteCheckIn === '1' && !clockInSuccess) return dialog.toast({title: '请完成定位'})
      Taro.showLoading({title: '交付任务中...'})
      const { data } = await updateOrderByTask({orderNumber, status: 3, taskDeliveryDescription: dialogContent, address, deliveryAccessories: uploadPath})
      Taro.hideLoading()
      Taro.showToast({title: '成功', icon: 'success', duration: 2000})
      setTimeout(() => {
        this.closeDialog(() => {
          this.selectMer()
        })
      }, 2000)
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  /**
   * @description 取消任务
   */
  cancelOrder = async (orderNumber) => {
    try {
      Taro.showLoading({mask: true, title: '取消中...'})
      const { data } = await updateOrderByTask({orderNumber, status: 7})
      Taro.hideLoading()
      dialog.toast({title: '取消成功'})
      this.setState({isDialog: false, dialogContent: ''}, () => {
        this.selectMer()
      })
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  changeDate = (e, type) => {
    let date = e.detail.value
    const { beginTime, endTime } = this.state
    switch (type) {
      case 'START':
        if (endTime) {
          let startTime = (new Date(date)).getTime()
          let footTime = (new Date(endTime)).getTime()
          if (startTime > footTime) {
            return Taro.showToast({ title: '开始时间不能大于结束时间', icon: 'none'})
          }
        }
        this.setState({beginTime: date})
        break
      default:
        if (beginTime) {
          let startTime = (new Date(beginTime)).getTime()
          let footTime = (new Date(date)).getTime()
          if (startTime > footTime) {
            return Taro.showToast({ title: '开始时间不能大于结束时间', icon: 'none'})
          }
        }
        this.setState({endTime: date})
        break
    }
  }

  handlerCheck = (item, index) => {
    this.state.taskList[index].checked = !item.checked
    this.setState({taskList: this.state.taskList})
  }

  getProtocol = async(id) => {
    try {
      Taro.showLoading({title: '正在跳转协议...'})
      const { data } = await getProtocolByTask({id})
      Taro.hideLoading()
      this.props.setUrl(data)
      Taro.navigateTo({url: '/pages/web/index'})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  goDetail = (taskNumber) => {
    Taro.navigateTo({url: '/pages/taskDetail/index?id=' + taskNumber})
  }

  uploadFile = () => {
    let _this = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        const tempFilePaths = res.tempFiles
        if (tempFilePaths[0].type !== 'file') return dialog.title({title: '请上传文件'})
        this.setState({uploadName: tempFilePaths[0].name, uploadPath: tempFilePaths[0].path})
      },
      fail(err) {
        dialog.toast({title: e.errMsg})
      }
    })
  }

  initUpload = () =>{
    this.setState({uploadPath: '', uploadName: ''})
  }

  render () {
    let { taskList, merchantName, dialogContent, beginTime, endTime, statusList, id, uploadName, uploadPath, address, checkedItem } = this.state;
    const tabList = [
      { title: '进行中', id: 0, status: 1 },
      { title: '已完成', id: 1, status: 2 },
      { title: '已取消', id: 2, status: 3 }
    ];
    return (
      <View className={styles.wrapper}>
        <View className={styles.headWrap}>
          <View className={styles.tabs}>
            {
              tabList.map((item, index)=>{
                return(
                  <View
                    className={id == item.status?`${styles.tab} ${styles.active}`:`${styles.tab}`}
                    onClick={() => this.selectTabs(item)}
                    key={item.id + ''}>
                    {item.title}
                  </View>
                )
              })
            }
          </View>
          <View className={styles.searchTime}>
            <View className={styles.searchWrap}>
              <Icon size='16' type='search' className={styles.myicon}/>
              <Input className={styles.inputs} type='text'
                    placeholder='请输入商户名称'
                    value={merchantName}
                    onInput={(e) => this.inputMer(e)}
              />
              <AtButton type='primary' size='small' onClick={()=>this.selectMer()}>搜索</AtButton>
            </View>
          </View>
          <View className={styles.timeWrapper}>
            <View className={styles.time}>
              <Picker mode="date" onChange={(e) => this.changeDate(e, 'START')}>
                <View className={styles.picker}>开始时间：<Text className={!beginTime ? styles.text : styles.theme}>{beginTime || '请选择时间'}</Text></View>
              </Picker>
            </View>
            <View className={styles.time}>
              <Picker mode="date" onChange={(e) => this.changeDate(e, 'END')}>
                <View className={styles.picker}>结束时间：<Text className={!endTime ? styles.text: styles.theme}>{endTime || '请选择时间'}</Text></View>
              </Picker>
            </View>
          </View>
        </View>
        <View className={styles.waitWrap}>
          {
            (taskList.length>0) ? taskList.map((item, index)=>{
            return(
              <View className={styles.order} key={index + ''} onClick={() => this.goDetail(item.taskNumber)}>
                <View className={styles.nameWrapper}>
                  <View className={styles.name}>{item.taskName}</View>
                  <View className={styles.status}>{statusList[item.status]}</View>
                </View>
                <View className={styles.decRe}>{item.taskDescribe}</View>
                <View className={styles.planEs}>
                  <View className={styles.planName}><Image className={styles.TriangleImg} src={SIGN_TIME_IMG} />任务时长：<Text className={styles.planTime}>{item.missionDuration}</Text></View>
                  <Text className={styles.esName}>预计费用：<Text className={styles.esTime}> {item.acceptanceAmount}</Text></Text>
                </View>
                <View className={styles.decRe}>接单时间：<Text>{item.createTime}</Text></View>
                <View className={styles.decRe}>起止时间：<Text> {item.taskBeginTime} 至 {item.taskEndTime}</Text></View>
                <View className={styles.Merchant}>发布商户： {item.merchantName}</View>
                {item.status !== 8 && <View className={styles.btnWrapper}>
                  {item.status === 2 && <Button type="warn" className={styles.cancel} onClick={(e) => {e.stopPropagation();this.cancelOrder(item.orderNumber)}}>取消任务</Button>}
                  <Button className={item.checked ? styles.confirm: `${styles.confirm} ${styles.disabled}`} onClick={(e) => {e.stopPropagation();this.confirm(item)}}>
                    {item.status === 2 ? '交付任务': item.status === 7 ? '重新接单': item.status === 4? '重新交付': '查看内容'}
                  </Button>
                </View>}
              </View>
            )
          }) : <NoData></NoData>
        }
        </View>
        <AtModal isOpened={this.state.isDialog} onClose={() => this.setState({isDialog : false})}>
          <AtModalContent>
            {
              this.state.isDialog && <Textarea
                placeholder='填写交付任务内容...'
                style={'width:100%;background:rgba(250, 250, 250, 1);border-radius: 2px;padding: 12px;box-sizing: border-box;height: 245px;'}
                placeholderStyle={'color: rgba(204, 204, 204, 1);font-size: 14px;'}
                maxlength={300}
                value={dialogContent}
                onInput={(e) => this.setState({dialogContent: e.detail.value})}>
              </Textarea>
            }
            <View className={styles.upload}>
              <Text className={styles.uploadText}>上传附件（微信里选择文件）</Text>
              {checkedItem.onSiteCheckIn === '1' && <Text className={styles.uploadText}>GPS定位</Text>}
            </View>
            <View className={styles.upload}>
              <View className={styles.item}>
                {
                  !uploadPath ? <View className={styles.fileUpload} onClick={this.uploadFile}></View> : <View className={styles.fileContent}>
                    <View className={styles.fileImg}><AtIcon value={'iconfont icon-file'} size={28}></AtIcon></View>
                    <Text>{uploadName}</Text>
                    <View className={styles.close} onClick={this.initUpload}><AtIcon value={'iconfont icon-close'} size={12} color="red"></AtIcon></View>
                  </View>
                }
              </View>
              {
                checkedItem.onSiteCheckIn === '1' && <View className={styles.item}>
                  {
                    address ? <Text>{address}</Text> : <View className={styles.clock} onClick={this.getSetting}>{'点击\n定位'}</View>
                  }
                </View>
              }
            </View>
          </AtModalContent>
          <AtModalAction><Button onClick={() => this.closeDialog()}>取消</Button><Button onClick={() => this.upLoadFileByFile()}>确定</Button> </AtModalAction>
        </AtModal>
        <AtModal isOpened={this.state.isContent} onClose={() => this.setState({isContent : false})}>
          <AtModalHeader>查看内容</AtModalHeader>
          <AtModalContent>
            <View style={'height: 430rpx;'}>{this.state.content}</View>
          </AtModalContent>
          <AtModalAction> <Button onClick={() => this.setState({isContent: false})}>确定</Button></AtModalAction>
        </AtModal>
      </View>
    )
  }
}
